package org.github.rayson517.easyplatform.common.web.jwt;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.github.rayson517.easyplatform.common.web.util.ThreadLocalUtil;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.log4j.Log4j2;

@Log4j2
@Component
public class JwtConfig {

	 /** 设置过期时间 */
    private static final long EXPIRATIONTIME = 1000 * 60 * 60 * 24 * 31L; // 1天
    
    /** jwt加密 */
    public static final String SECRET = "test";
    
    /** token前缀 */
    public static final String TOKEN_PREFIX = "Bearer";
    /** token请求头串 */
    public static final String HEADER_STRING = "Authorization";
   
	public long getEXPIRATIONTIME() {
		return EXPIRATIONTIME;
	}

	public String getSECRET() {
		return SECRET;
	}

	public String getTOKEN_PREFIX() {
		return TOKEN_PREFIX;
	}

	public String getHEADER_STRING() {
		return HEADER_STRING;
	}

	public String addToken(HttpServletResponse res, Map<String, Object> map) {
	      String token = Jwts.builder()
	              .setClaims(map)
	              .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
	              .signWith(SignatureAlgorithm.HS512, SECRET)
	              .compact();
	      String tokenString = TOKEN_PREFIX + " " + token;
	      res.addHeader(HEADER_STRING, tokenString);
	      	return tokenString;
		}
	
	public Claims getToken(HttpServletRequest request){
		String token = request.getHeader(HEADER_STRING);
       
       if(token == null){
           token = request.getParameter("token");
       }
       if(log.isDebugEnabled()){
       	log.info(">>>>Token:{}", token);
       }
       
       if (token == null) 
       	return null;
       
       ThreadLocalUtil.setValue("token", token);  // 用户id
       
       Claims claims = Jwts.parser()
               .setSigningKey(SECRET)
               .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
               .getBody();

       return claims;
	}
}
